package com.py.longtrans;

import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 类说明 sftp工具类
 */
public class SFTPUtil {

    private ChannelSftp sftp;

    private Session session;
    /** SFTP 登录用户名*/
    private String username;
    /** SFTP 登录密码*/
    private String password;
    /** 私钥 */
    private String privateKey;
    /** SFTP 服务器地址IP地址*/
    private String host;
    /** SFTP 端口*/
    private int port;

    private static Logger logger = LoggerFactory.getLogger(SFTPUtil.class);

    /**
     * 构造基于密码认证的sftp对象
     */
    public SFTPUtil(String username, String password, String host, int port) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
    }

    public SFTPUtil(){}


    /**
     * 连接sftp服务器
     */
    public void login(){
        try {
            JSch jsch = new JSch();
            if (privateKey != null) {
                jsch.addIdentity(privateKey);// 设置私钥
            }

            session = jsch.getSession(username, host, port);

            if (password != null) {
                session.setPassword(password);
            }
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");

            session.setConfig(config);
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();

            sftp = (ChannelSftp) channel;
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接 server
     */
    public void logout(){
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }


    /**
     * 将输入流的数据上传到sftp作为文件。文件完整路径=basePath+directory
     * @param basePath  服务器的基础路径
     * @param directory  上传到该目录
     * @param sftpFileName  sftp端文件名
     * @param
     */
    public void upload(String basePath,String directory, String sftpFileName, InputStream input) throws SftpException{
        try {
            logger.info("进入"+basePath+"目录，准备上传");
            sftp.cd(basePath);
//            sftp.cd(directory);
        } catch (SftpException e) {
            //目录不存在，则创建文件夹
            logger.error(e.toString());
            logger.error("目录不存在！");
        }
        sftp.put(input, sftpFileName);  //上传文件
    }


    /**
     * 下载文件。
     * @param directory 下载目录
     * @param downloadFile 下载的文件
     * @param saveFile 存在本地的路径,带文件名
     */
    public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException {
        if (directory != null && !"".equals(directory)) {
            sftp.cd(directory);
        }
        File file = new File(saveFile);
        sftp.get(downloadFile, new FileOutputStream(file));
    }


    /**
     * 删除文件
     * @param directory 要删除文件所在目录
     * @param deleteFile 要删除的文件
     */
    public void delete(String directory, String deleteFile) throws SftpException{
        sftp.cd(directory);
        sftp.rm(deleteFile);
    }


    /**
     * 列出目录下的文件
     * @param directory 要列出的目录
     */
    public Vector<?> listFiles(String directory) throws SftpException {
        return sftp.ls(directory);
    }


    public static void uploadExl(){
        ResourceBundle resource = ResourceBundle.getBundle("path");  // 读取自定义配置文件
        final BASE64Decoder decoder = new BASE64Decoder();
        String sftpPassword = resource.getString("sftp.password");
        String password = null;
        try {
            password = new String(decoder.decodeBuffer(sftpPassword), "UTF-8");
            logger.info("sftp密码解码完毕！");
        } catch (IOException e) {
            logger.error(e.toString());
        }
//        System.out.println("密码(后续删除):"+password);
        String userName = resource.getString("sftp.username");
        String address = resource.getString("sftp.address");
        int port = Integer.valueOf(resource.getString("sftp.port"));
        String path = resource.getString("path.sftp");
        String filePath = resource.getString("path.out");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Date date = new Date();
        String s = df.format(date);// new Date()为获取当前系统时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)-1);
        date = calendar.getTime();
        String accDate = df.format(date);
        String s1 = accDate.split(" ")[0];

        String chkFilePath = filePath+s1.replaceAll("-","")+"_00.chk";
        filePath = filePath+s1.replaceAll("-","")+"_00.txt";
        String chkPath = path+s1.replaceAll("-","")+"_00.chk";
        path = path+s1.replaceAll("-","")+"_00.txt";
        File file = new File(filePath);
        logger.info("txt文件名称："+filePath);
        File chkfile = new File(chkFilePath);
        logger.info("chk文件名称："+chkFilePath);
        try {
            logger.info("读取文件");
            System.out.println("读取文件");
            InputStream is = new FileInputStream(file);
            InputStream chkIs = new FileInputStream(chkfile);
            System.out.println("读取文件完毕");
            logger.info("读取文件完毕");
            SFTPUtil sftp = new SFTPUtil(userName, password, address, port);
            logger.info("sftp接入");
            sftp.login(); //sftp登入
            logger.info("sftp接入完毕，开始上传");
            sftp.upload("/incoming/EC-DATA/006/","", path, is); // 基础路径  路径下文件夹  上传文件路径  输出流
            sftp.upload("/incoming/EC-DATA/006/","", chkPath, chkIs);
            logger.info("上传完毕");
            sftp.logout();
        } catch (FileNotFoundException | SftpException e) {
            logger.error(e.toString());
        }
        logger.info("日传完成！");
    }

    public static void uploadMonth(){
        ResourceBundle resource = ResourceBundle.getBundle("path");  // 读取自定义配置文件

        final BASE64Decoder decoder = new BASE64Decoder();
        String sftpPassword = resource.getString("sftp.password");
        String password = null;
        try {
            password = new String(decoder.decodeBuffer(sftpPassword), "UTF-8");
            logger.info("sftp密码解码完毕！");
        } catch (IOException e) {
            logger.error(e.toString());
        }
        String userName = resource.getString("sftp.username");
        String address = resource.getString("sftp.address");
        int port = Integer.valueOf(resource.getString("sftp.port"));
        System.out.println("端口:"+port);
        String path = resource.getString("path.monthsftp");
        String filePath = resource.getString("path.monthout");

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        SimpleDateFormat mf = new SimpleDateFormat("yyyyMM");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
        date = calendar.getTime();
        String accDate = mf.format(date); // 上个月 202201
        String s = df.format(new Date());// new Date()为获取当前系统时间
        String s1 = s.split(" ")[0];

        String txtPath = filePath+accDate+"_00.txt";
        String sftpTxtPath = path+accDate+"_00.txt";
        String chkPath = filePath+accDate+"_00.chk";
        String sftpMonthPath = path+accDate+"_00.chk";

        File txtfile = new File(txtPath);
        logger.info("月传txt文件路径:"+txtPath);
        File chkfile = new File(chkPath);
        logger.info("月传chk文件路径："+chkPath);
        try {
            logger.info("月传io读取文件");
            InputStream is = new FileInputStream(txtfile);
            InputStream chkIs = new FileInputStream(chkfile);
            logger.info("月传io读取文件完毕");
            SFTPUtil sftp = new SFTPUtil(userName, password, address, port);
            logger.info("月传登入sftp");
            sftp.login(); //sftp登入
            logger.info("月传登入sftp完毕，开始上传");
            sftp.upload("/incoming/EC-DATA/006/","", sftpTxtPath, is); // 基础路径  路径下文件夹  上传文件路径  输出流
            sftp.upload("/incoming/EC-DATA/006/","", sftpMonthPath, chkIs);
            logger.info("月传上传完毕！登出sftp账号");
            sftp.logout();
            logger.info("登出完毕");
        } catch (FileNotFoundException | SftpException e) {
            logger.error(e.toString());
        }

        logger.info("月传完成！");
    }
}